import axios from "axios";
import store from '../store'
import PromptInfo from "../utils/notification.js";

const tokenPrefix='Bearer ';
const baseURL=import.meta.env.VITE_API_HOST //导入env中的变量

const instance =axios.create({
    baseURL
})
//让请求都带上token
instance.interceptors.request.use(
    config=>{
        //如果有token就把token放进去
        if (store.state.user.token){
            config.headers['Authorization']=tokenPrefix+store.state.user.token;
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(
    response=>{
        if (response.data.code){  //在后端只有报错才会有code
            handlerResponse(response);
            return Promise.reject(response.data)
        }

        return response.data;
},
    error => {
        // if (!error.response){
        //     PromptInfo.error("无网络或服务器异常")
        // }
        console.log(error)
        handlerResponse(error.response)

        return Promise.reject(error)
    })

const handlerResponse=response=>{
    if (response.status===401||response.status===403){
        store.dispatch('user/logout').then(()=>window.location.reload());
    }

    if (response.data instanceof Array){
        response.data.forEach(item=>{
           PromptInfo.error(item.message)
        })
    }else{
        PromptInfo.error(response.data.message)
    }


}


const {get,post,put} = instance

export {get,post,put}
